<template>
  <div class="answer-editor">
    <!-- 判断题 -->
    <template v-if="questionType === 1">
      <el-radio-group v-model="localAnswer" @change="handleChange">
        <el-radio :label="'1'">正确</el-radio>
        <el-radio :label="'0'">错误</el-radio>
      </el-radio-group>
    </template>

    <!-- 单选题 -->
    <template v-else-if="questionType === 2">
      <el-radio-group v-model="localAnswer" @change="handleChange">
        <el-radio 
          v-for="option in parsedOptions" 
          :key="option.label" 
          :label="option.label"
        >
          {{option.label}}. {{option.value}}
        </el-radio>
      </el-radio-group>
    </template>

    <!-- 多选题 -->
    <template v-else-if="questionType === 3">
      <el-checkbox-group v-model="localAnswers" @change="handleMultiChange">
        <el-checkbox 
          v-for="option in parsedOptions" 
          :key="option.label" 
          :label="option.label"
        >
          {{option.label}}. {{option.value}}
        </el-checkbox>
      </el-checkbox-group>
    </template>

    <!-- 其他题型 -->
    <template v-else>
      <el-input 
        v-model="localAnswer"
        type="textarea"
        :rows="3"
        placeholder="请输入答案"
        @change="handleChange"
      />
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';

const props = defineProps<{
  modelValue: string;
  questionType: number;
  options?: string;
}>();

const emit = defineEmits(['update:modelValue']);

const localAnswer = ref('');
const localAnswers = ref<string[]>([]);

// 解析选项
const parsedOptions = computed(() => {
  if (!props.options) return [];
  try {
    return JSON.parse(props.options);
  } catch {
    return [];
  }
});

// 监听答案变化
watch(() => props.modelValue, (newVal) => {
  if (props.questionType === 3) {
    try {
      localAnswers.value = JSON.parse(newVal);
    } catch {
      localAnswers.value = [];
    }
  } else {
    localAnswer.value = newVal;
  }
}, { immediate: true });

// 处理单个答案变化
const handleChange = (val: string) => {
  emit('update:modelValue', val);
};

// 处理多选答案变化
const handleMultiChange = (val: string[]) => {
  emit('update:modelValue', JSON.stringify(val));
};
</script> 